// pages/home/category/uploadCTdata/orderpay/orderpay.js
import util from '../../../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isNeedBill: 0,
    orderId:'',
    orderPrice:'',
    updateInvoice:{
      order_id:'',
      payer_type:0,
    },
    time:'',
    invoiceType:'普通发票',
    invoicePop:true,
    popupConfig: {
      title: '发票'
    },
    invoiceId:'',
    taxpayer_code_tips:false,
    invoiceList:[],
    invoice:{
      type: 3,
      invoice_type: 1,
      invoice_title: '',
      taxpayer_code: '',
      address: {phone: '', email: ''},
      registered_address: '',
      registered_phone: '',
      bank_name: '',
      bank_account: '',
      taxpayers_certificate_id: '',  //增值税复印件
      business_license_id: '', //营业执照
      account_permit_id: ''   //开户许可
    },
    isEdit: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self=this
    self.setData({
       orderId: options.id,
       orderPrice: options.price
     })
    self.findAllInvoice()
    //循环是为了解决该订单是否已经支付完成了
    var setTime = setInterval(function () {  
      self.getOrderDetails()
    }, 2000)
    self.setData({
      time: setTime
    })
    wx.eventBus.on('seeTaxpayer', (res) => {
      self.setData({
        taxpayer_code_tips: res
      })
    })
    wx.eventBus.on('findAllInvoiceList', (res) => {
      self.findAllInvoice()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self = this
    self.findAllInvoice()
    wx.eventBus.trigger('getInvoiceAddress', 'address')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      time: clearInterval(this.data.time)  
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      time: clearInterval(this.data.time)
    })  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //关闭纳税人识别码说明
  closeTaxpayer: function () {
    this.setData({
      taxpayer_code_tips: false
    })
  },
  // 点击微信支付
  wxPay () {
    this.updatePayerInfo()
  },
  // 发起微信支付
  callPayMent (params) {
    console.log('params', params)
    var me = this
    wx.requestPayment({
      'timeStamp': params.timeStamp,
      'nonceStr': params.nonceStr,
      'package': params.pkg,
      'signType': 'MD5',
      'paySign': params.paySign,
      'success':function (res) {
        console.log('支付成功',res)
        wx.showToast({
          title: '支付成功'
        })
        wx.redirectTo({
          url: '../../../../order/orderDetail/orderDetail?id=' + me.data.orderId
        })
      },
      'fail':function (res) {
        console.log('支付失败', res)
      }
    })
  },
  // 获取支付信息
  getPayInfo () {
    let host = wx.envConfig.host
    var openid = getApp().globalData.openid
    if (!openid) {
      throw new Error('openid不能为空')
    }
    wx.request({
      url: host + '/wechatpay/miniProgramPay?params=' + JSON.stringify({orderId: this.data.orderId, openid: openid})  + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: (res) => {
        console.log('获取支付信息', res.data)
        var datas = res.data.datas
        this.callPayMent({
          timeStamp: datas.timeStamp,
          nonceStr: datas.nonceStr,
          pkg: 'prepay_id=' + datas.prepayId,
          paySign: datas.paySign
        })
      },
      fail: (err) => {
        console.log('err', err)
      }
    })
  },
  /**
   * 点击radio
   */
  choose: function (event) {
    let self = this
    if (event.currentTarget.dataset.index==2){
      wx.showModal({
        title: '提示',
        confirmText: '是',
        cancelText: '否',
        cancelColor: '#4825BF',
        confirmColor: '#4825BF',
        content: '您选择不需要发票，付款成功后，将不再提供发票开具申请，是否确认不需要？',
        success: function (res) {
          if (res.confirm) {
            self.setData({
              isNeedBill: event.currentTarget.dataset.index,
              invoiceList: self.data.invoiceList.map(it => {
                it.check = false
                return it
              })
            })
          } else if (res.cancel) {
            self.setData({
              isNeedBill: 1,
            })
          }
        }
      })
    }else{
      this.setData({
        isNeedBill: event.currentTarget.dataset.index
      })
    }
  },
  addInvoice:function(){
    this.setData({
      invoicePop: false,
    })
    wx.eventBus.trigger('addInvoiceInfo', {
      type: 3,
      invoice_type: 1,
      invoice_title: '',
      taxpayer_code: '',
      address: { phone: '', email: '' },
      registered_address: '',
      registered_phone: '',
      bank_name: '',
      bank_account: '',
      taxpayers_certificate_id: '',  //增值税复印件
      business_license_id: '', //营业执照
      account_permit_id: ''   //开户许可
    })
  },
  /**
   * 点击前往发票选择
   */
  chooseBill: function () {
    wx.navigateTo({
      url: './billinfo/billinfo?id='+this.data.orderId,
    })
  },
  // 微信支付
  payOrder: function () {
    let self = this
    var updateInvoice = self.data.updateInvoice
    if (self.data.isNeedBill == 0 || self.data.isNeedBill == 2) {
      updateInvoice.invoice_id = '-1'
    } else {
      self.data.invoiceList.forEach(function (item) {
        if (item.check == true) {
          updateInvoice.invoice_id = item.id
        }
      })
      if (self.data.isNeedBill == '1' && (updateInvoice.invoice_id == '-1' || !updateInvoice.invoice_id)) {
        wx.showToast({
          title: '请选择发票',
          icon: 'none',
          duration: 1000,
          mask: true
        })
        return
      }
    }
    wx.showModal({
      title: '支付说明',
      confirmText: '同意',
      cancelText: '不同意',
      cancelColor: '#999999',
      confirmColor: '#4825BF',
      content: '您已知晓并确认此支付为医生与患者充分沟通获得患者授权后的行为，本公司提供的服务是仅面向前述客户的数据处理服务，对任何病人不存在任何形式的约定或承诺，本公司不参与手术方案的制定和手术实施过程，对手术方案或手术实施中存在的瑕疵、失误、错误及由此导致的任何损害或损失，本公司不承担任何责任，关于手术相关的任何疑问请咨询患者主治医师。',
      success: function (res) {
        if (res.confirm) {
          updateInvoice.order_id = self.data.orderId
          self.setData({
            updateInvoice: updateInvoice
          })
          wx.request({
            url: wx.envConfig.host + '/order/updateOrderRaw?params=' + JSON.stringify(self.data.updateInvoice) + '&cookiez=' + wx.getStorageSync('cookiez'),
            method: 'POST',
            success: function (ress) {
              console.log('ress```', ress)
              if (ress.data.error_code === "Y10000") {
                self.getPayInfo()
              }
            },
            fail: function ({ errMsg }) {
              console.log('request fail', errMsg)
            }
          })
        } else if (res.cancel) {
            
        }
      }
    })
    
  },
  //判断该订单是否被支付
  getOrderDetails:function(){
    let self=this
    wx.request({
      url: wx.envConfig.host + '/order/findByOrder?params=' + JSON.stringify({ "order_id": self.data.orderId }) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        if (res.data.error_code === "Y10000") {
          if (res.data.datas.serviceInfo.pay_status == 1){
            wx.showToast({
              title:'订单已支付，将为您跳转订单详情',
              icon:'none',
              mask:true,
              complete:function(){
                wx.redirectTo({
                  url: '../../../../order/orderDetail/orderDetail?id=' + self.data.orderId
                })
              }
            })
            self.setData({
              time: clearInterval(self.data.time)
            })
          }
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //获取该订单是否有发票信息
  findAllInvoice:function(){
    let self = this
    wx.request({
      url: wx.envConfig.host + '/invoice/findAll' + '?cookiez=' + wx.getStorageSync('cookiez'),
      method: 'GET',
      success: function (res) {
        if (res.data.error_code == 'Y10000') {
          self.setData({
            invoiceList: res.data.datas.map(it => {
              it.scrollLeft = 0
              it.check = false
              it.invoice_address = JSON.parse(it.invoice_address)
              return it
            })
          })
        } else {
          wx.showToast({
            title: '获取订单失败',
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //编辑发票信息
  editInvoice:function(e){
    let self = this
    wx.request({
      url: wx.envConfig.host + '/invoice/get?params=' + JSON.stringify({ id: e.currentTarget.dataset.item})+'&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'GET',
      success: function (res) {
        if (res.data.error_code == 'Y10000') {
            res.data.datas.address = JSON.parse(res.data.datas.invoice_address)
            self.setData({
              invoice:res.data.datas,
              invoicePop:false,
              isEdit:true
            })
            wx.eventBus.trigger('editInvoiceInfo', self.data.invoice)
        } else {
          wx.showToast({
            title: '获取订单失败',
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //删除发票
  delInvoice:function(e){
    let self = this
    wx.request({
      url: wx.envConfig.host + '/invoice/' + e.currentTarget.dataset.item + '?cookiez=' + wx.getStorageSync('cookiez'),
      method: 'DElETE',
      success: function (res) {
        if (res.data.error_code == 'Y10000') {
          self.findAllInvoice()
        } else {
          wx.showToast({
            title: '删除发票失败',
            icon:null,
            duration: 1000,
            mask: true
          })
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  //选择发票
  chooseInvoice:function(e){
    var self=this
    self.setData({
      invoiceList: self.data.invoiceList.map(it => {
        it.check = it.id == e.currentTarget.dataset.item.id ? true : false
        self.setData({
          invoiceId: it.check ? it.id : ''
        })
        return it
      })
    })
  },
  //保存订单信息
  saveInvoiceInfo:function(){
    wx.eventBus.trigger('getInvoiceInfo', this.data.invoice)
  }
})